package com.foolishbird.sdk.ui.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.foolishbird.sdk.core.HttpEngineApi;
import com.foolishbird.sdk.params.FloatKefuResponseParams;
import com.foolishbird.sdk.params.RedBindedResponseParams;
import com.foolishbird.sdk.params.RedDetailResponseParams;
import com.foolishbird.sdk.params.RedGetResponseParams;
import com.foolishbird.sdk.params.ResponseParams;
import com.foolishbird.sdk.params.bean.RedBindedInfo;
import com.foolishbird.sdk.params.bean.RedDetailInfo;
import com.foolishbird.sdk.params.bean.State;
import com.foolishbird.sdk.ui.assist.OnFinishActivityListener;
import com.foolishbird.sdk.utils.MyFragmentManger;
import com.foolishbird.sdk.utils.ResUtils;
import com.foolishbird.sdk.utils.WL;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


public class RedpackageDetailFragment extends BaseHttpFragment implements View.OnClickListener {


    private ListView mListview;
    private TextView titleTxt;

    private ImageView backView;
    private  BaseAdapter mAdapter;

    public static final RedpackageDetailFragment newInstance(Bundle bundle) {
        RedpackageDetailFragment fragment = new RedpackageDetailFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        int resource = ResUtils.getLayoutIdentifier(getActivity(), "fb_redpackage_detail");
        View contentView =inflater.inflate(resource,null);
        backView = contentView.findViewById(getViewIdentifier("fb_fragment_login_back"));
        backView.setOnClickListener(this);
        titleTxt = contentView.findViewById(getViewIdentifier("fb_fragment_float_title"));
        titleTxt.setText("红包明细");
        mListview = contentView.findViewById(getViewIdentifier("float_notice_list"));
        mListview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                //如果最后一个可见item等于总的item，且当前滚动状态为滚动停止，就应该开始加加载数据了
                if(lastVisibleItem == totalItemCount && scrollState==SCROLL_STATE_IDLE){
                    if(!isLoading){
                        isLoading = true;
                        page++;
                        loadData();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int itemCount) {
                lastVisibleItem = firstVisibleItem + visibleItemCount;
                totalItemCount = itemCount;
            }
        });
        page=1;
        loadData();
//        HttpEngineApi.getInstance().redpackageCommon("my_bind",requestCallbackHandler(RedBindedResponseParams.class));
        return contentView;

    }

    private void loadData(){
        HttpEngineApi.getInstance().redpackageDetail(page,requestCallbackHandler(RedDetailResponseParams.class));
    }

    private int page =1,lastVisibleItem,totalItemCount;
    private boolean isLoading = true;

    private List<RedDetailInfo> myNoticeList;

    @Override
    public void onAsyncRequestResult(int flag, ResponseParams response, Object... params) {
        super.onAsyncRequestResult(flag, response, params);
        if (response != null) {
            int code = response.getState().getCode();
            if (State.SUCCESS == code) {
                if(response instanceof RedDetailResponseParams){
                    isLoading = false;
                    if(page==1){
                        myNoticeList =((RedDetailResponseParams)response).getData().getRedPackageInfos();
                    }else {
                        if(myNoticeList==null)return;
                        myNoticeList.addAll(((RedDetailResponseParams)response).getData().getRedPackageInfos());
                    }

                }
            }
            setAdapter();
        }



        WL.d("FloatNoticeFragment",response.toString());
    }

    private int deleteTaskId;

    private void setAdapter(){

        if (mAdapter==null){
            mAdapter = new BaseAdapter() {
                @Override
                public int getCount() {
                    return myNoticeList==null?0:myNoticeList.size();
                }

                @Override
                public Object getItem(int i) {
                    return myNoticeList.get(i);
                }

                @Override
                public long getItemId(int i) {
                    return i;
                }

                @Override
                public View getView(int i, View view, ViewGroup viewGroup) {
                    ViewHolder holder = null;
                    if (view == null) {
                        int resource = ResUtils.getLayoutIdentifier(getContext(), "fb_redpackage_detail_item");
                        view = LayoutInflater.from(getContext()).inflate(resource, null);
                        holder = new ViewHolder();
                        holder.timeText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_detail_time"));
                        holder.typeText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_detail_type"));
                        holder.moneyText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_detail_money"));
//                        holder.deleteText = (TextView) view.findViewById(ResUtils.getViewIdentifier(getContext(), "redpackage_binded_delete"));

                        view.setTag(holder);
                    } else {
                        holder = (ViewHolder) view.getTag();
                    }
                    RedDetailInfo info = myNoticeList.get(i);

                    holder.typeText.setText(info.getMemo());
                    try {
                        holder.timeText.setText(sdf2.format(sdf1.parse(info.getCreatedAt())));
                    }catch (Exception e){
                        holder.timeText.setText(info.getCreatedAt());
                    }
                    String money = info.getMoney();
                    if(!money.contains("-")&&!money.contains("+")){
                        holder.moneyText.setText("+"+info.getMoney());
                    }else{
                        holder.moneyText.setText(info.getMoney());
                    }
//                    holder.moneyText.setText(info.getMoney().contains("-")?info.getMoney():"+"+info.getMoney());




                    return view;
                }
            };
            mListview.setAdapter(mAdapter);
        }
        mAdapter.notifyDataSetChanged();
    }

    class ViewHolder {
        TextView timeText;
        TextView typeText;
        TextView moneyText;
    }

    SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdf2=new SimpleDateFormat("yyyy.MM.dd");

    @Override
    public void onClick(View view) {
        if(view ==backView){
            MyFragmentManger.getInstance().goBack(this);
        }
//        OnFinishActivityListener listener = getOnFinishActivityListener();
//        if (listener != null) {
//            listener.doFinishActivity(this);
//        }
    }

    private OnFinishActivityListener getOnFinishActivityListener() {
        if (!isNullContext()) {
            Activity activity = getActivity();
            if (activity instanceof OnFinishActivityListener) {
                return (OnFinishActivityListener) activity;
            }
        }
        return null;
    }
}
